<?php
namespace app\common\traits;

trait Curd
{
    /**
     * 根据主键来操作
     */
    public function save($params)
	{
        $pk = $this->model->getPk();
        // dump($params);return;

		try {
            if ( ! empty($params[$pk])) {
                $where[$pk] = $params[$pk];

                if ( ! $this->model->where($where)->find()) {
                    $this->errorMsg = '数据不存在';                    
                    return false;
                }

                $this->model->editData($where, $params);
            }else {
                // 新增
                if ( ! $this->model->addData($params)) {
                    throw new \Exception('新增失败');
                }
			}

			return true;
		}catch (\Exception $e) {

			$this->errorMsg = $e->getMessage();
			return false;
		}
    }

    /**
     * 根据主键来操作，可以传主键集合
     */
    public function get($params)
	{
        $pk = $this->model->getPk();

        if (empty($params[$pk])) {
            return [];
        }
        
        $where[$pk] = $params[$pk];
        $row = $this->model->where($where)->findArray();
        if ($row) {
            foreach ($row as $key => $value) {
                if (isTimestamp($value)) {
                    $row[$key] = date('Y-m-d H:i:s',$value);
                }
            }
        }

        return $row;
	}

    /**
     * 根据主键来操作，可以传主键集合
     */
    public function delete($params)
	{
        try {
            $pk = $this->model->getPk();
            if (empty($params[$pk])) {
                throw new \Exception("ID数据不存在");
            }

            $rs = $this->model->where(['id' => $params['id']])->delete();
            if ( ! $rs) {
                throw new \Exception("操作失败");
            }

            return true;
        }catch (\Exception $e) {
			$this->errorMsg = $e->getMessage();
			return false;
		}
	}
}